<?php
declare (strict_types=1);

namespace app\common\model;

class Evaluate extends Base
{
    protected $name = 'evaluate';


    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,nickname,photo');
    }


    public static function addEvaluatet($param,$user){
        parent::startTrans();
        try {

            $order=Order::where(['id'=>$param['order_id'],'is_del'=>0])->find();
            if(empty($order)){
                return ['code' => -1,'msg'=>'该订单不存在！'];
            }
            if($order->getData('status') != 3){
                return ['code' => -1,'msg'=>'该订单不可评价！'];
            }
            if($order->uid != $user->id){
                return ['code' => -1,'msg'=>'非本人订单不可评价！'];
            }
            foreach($param['list'] as $k=>$v){
                $find=parent::where(['product_id'=>$v['pid'],'order_id'=>$param['order_id'],'uid'=>$user->id])->find();
                if(empty($find)){
                    $data['create_time']=time();
                    $data['uid']=$user->id;
                    $data['product_id']=$v['pid'];
                    $data['order_id']=$param['order_id'];
                    if(!empty($v['content'])){
                        $data['content']=$v['content'];
                    }else{
                        $data['content']='该用户没有填写评价，但认为该商品值得购买！';
                    }

                    $data['images'] = $v['images'];

                    if($v['pronum']==0){
                        $data['pronum']=5;
                    }else{
                        $data['pronum']=$v['pronum'];
                    }
                    $instAll[]=$data;
                }
            }
            if (!empty($instAll)) {
                parent::insertAll($instAll);
                $order->status=4;
                $order->save();
            }
            parent::commit();
            return ['code' => 1,'msg'=>'评价成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
